<template>
  <div>
    <!-- 表单弹窗 -->
    <el-dialog
      v-model="showFormDialog"
      title="数据使用申请"
      width="800px"
      :before-close="handleCloseForm"
    >
      <el-form
        :disabled="category"
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="150px"
      >
        <!-- <el-form-item label="表单类型" prop="applicationType">
          <el-select v-model="formData.applicationType" disabled>
            <el-option label="ETL" value="1" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="申请标题" prop="applicationTitle">
          <el-input v-model="formData.applicationTitle" placeholder="请输入申请标题" />
        </el-form-item>
        <el-form-item label="申请原因" prop="applicationReason">
          <el-input
            v-model="formData.applicationReason"
            type="textarea"
            :rows="3"
            placeholder="请输入申请原因"
          />
        </el-form-item>
        <el-form-item label="应用场景" prop="applicationScenario">
          <el-input
            v-model="formData.applicationScenario"
            type="textarea"
            :rows="2"
            placeholder="请输入数据的应用场景"
          />
        </el-form-item>
        <el-form-item label="使用时间" prop="useTime">
          <el-date-picker
            v-model="formData.useTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系地址" prop="contactAddress">
          <el-input v-model="formData.contactAddress" placeholder="请输入联系地址" />
        </el-form-item>
        <el-form-item label="服务范围" prop="serviceScope">
          <el-input
            v-model="formData.serviceScope"
            type="textarea"
            :rows="2"
            placeholder="基于开发数据开发的应用上线之后的用户群体以及对应的服务范围"
          />
        </el-form-item>
        <el-form-item label="预期成效" prop="expectedEffect">
          <el-input
            v-model="formData.expectedEffect"
            type="textarea"
            :rows="2"
            placeholder="基于开放数据开发的应用上线之后的社会效益、经济效益"
          />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="formData.systemName" placeholder="使用开放数据的业务系统名称" />
        </el-form-item>
        <el-form-item label="部署地点" prop="deploymentLocation">
          <el-input
            v-model="formData.deploymentLocation"
            placeholder="使用开放数据的业务系统部署地点/机房地址"
          />
        </el-form-item>
        <el-form-item label="系统IP" prop="systemIp">
          <el-input v-model="formData.systemIp" placeholder="使用开放数据的业务系统IP" />
        </el-form-item>
        <el-form-item label="系统URL" prop="systemUrl">
          <el-input v-model="formData.systemUrl" placeholder="使用开放数据的业务系统URL地址" />
        </el-form-item>
        <el-form-item label="等保备案编号" prop="levelProtectionCode">
          <el-input
            v-model="formData.levelProtectionCode"
            placeholder="使用开放数据的业务系统等级保护备案编号"
          />
        </el-form-item>
        <el-form-item label="等保级别" prop="levelProtectionLevel">
          <el-select v-model="formData.levelProtectionLevel" placeholder="请选择等保级别">
            <el-option
              v-for="item in levelProtectionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="承诺书" prop="commitmentFile">
          <UploadFile
            v-model="formData.commitmentFile"
            :file-type="['pdf']"
            :file-size="10"
            :limit="1"
            :is-show-tip="true"
            :typeDownload="'1'"
          />
        </el-form-item>
        <el-form-item label="申请书" prop="applyFile">
          <UploadFile
            v-model="formData.applyFile"
            :file-type="['pdf']"
            :file-size="10"
            :limit="1"
            :is-show-tip="true"
            :typeDownload="'2'"
          />
        </el-form-item>
        <!-- <el-form-item label="调用次数限制" prop="callCountLimit">
          <el-input v-model.number="formData.callCountLimit" placeholder="请输入调用次数限制" />
        </el-form-item>
        <el-form-item label="调用间隔(秒)" prop="callIntervalSeconds">
          <el-input
            v-model.number="formData.callIntervalSeconds"
            placeholder="请输入调用间隔(秒)"
          />
        </el-form-item> -->
        <el-form-item v-if="type == '1'" label="目标数据库地址" prop="targetDatabaseAddress">
          <el-input
            v-model="formData.targetDatabaseAddress"
            placeholder="请输入目标数据库地址，账号等信息"
          />
        </el-form-item>
        <el-form-item v-if="type == '1'" label="目标数据库表名" prop="targetDatabaseTableName">
          <el-input v-model="formData.targetDatabaseTableName" placeholder="请输入目标数据库表名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseForm">取消</el-button>
          <el-button type="primary" v-if="!category" @click="handleSubmit('1')">提交申请</el-button>
          <el-button type="primary" v-if="!category" @click="handleSave('0')">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import * as portalApi from '@/api/portal'
import UploadFile from '@/components/UploadFile/src/UploadFile.vue'

import { useRoute } from 'vue-router'

const emit = defineEmits(['formSubmitted'])

const route = useRoute()

// 定义DictOption接口
interface DictOption {
  label: string
  value: string
}

const props = defineProps({
  // 可以传入数据相关信息
  dataInfo: {
    type: Object,
    default: () => ({})
  }
})

// 弹窗控制
const showFormDialog = ref(false)
const formRef = ref<FormInstance>()
const levelProtectionOptions = ref<DictOption[]>([])

// 表单数据，默认表单类型为1
const formData = reactive({
  applicationType: '1', // 默认ETL类型
  applicationTitle: '',
  applicationReason: '',
  applicationScenario: '',
  useTime: [] as [string, string],
  contactPhone: '',
  contactAddress: '',
  serviceScope: '',
  expectedEffect: '',
  systemName: '',
  deploymentLocation: '',
  systemIp: '',
  systemUrl: '',
  levelProtectionCode: '',
  levelProtectionLevel: '',
  commitmentFile: '', // 承诺书文件
  applyFile: '', // 申请书文件
  targetDatabaseAddress: '',
  targetDatabaseTableName: ''
})

// 表单验证规则
const formRules: FormRules = {
  applicationType: [{ required: true, message: '请选择表单类型', trigger: 'change' }],
  applicationTitle: [{ required: true, message: '请输入申请标题', trigger: 'blur' }],
  applicationReason: [{ required: true, message: '请输入申请原因', trigger: 'blur' }],
  applicationScenario: [{ required: true, message: '请输入数据的应用场景', trigger: 'blur' }],
  useTime: [{ required: true, message: '请选择使用时间', trigger: 'change' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactAddress: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
  serviceScope: [
    {
      required: true,
      message: '基于开发数据开发的应用上线之后的用户群体以及对应的服务范围',
      trigger: 'blur'
    }
  ],
  expectedEffect: [
    {
      required: true,
      message: '基于开放数据开发的应用上线之后的社会效益、经济效益',
      trigger: 'blur'
    }
  ],
  commitmentFile: [{ required: true, message: '请上传承诺书', trigger: 'change' }],
  applyFile: [{ required: true, message: '请上传申请书', trigger: 'change' }],
  targetDatabaseAddress: [
    { required: true, message: '请输入目标数据库地址，账号等信息', trigger: 'blur' }
  ],
  targetDatabaseTableName: [{ required: true, message: '请输入目标数据库表名', trigger: 'blur' }]
}

// 打开表单弹窗
const openForm = () => {
  showFormDialog.value = true
}

// 关闭表单弹窗
const handleCloseForm = () => {
  showFormDialog.value = false
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 获取等保级别字典数据
const getLevelProtectionOptions = async () => {
  try {
    const res = await portalApi.getDictByCode({ dictType: 'protectionLevel' })
    if (res) {
      // 假设返回的数据格式为 { data: [{ label: '一级', value: '一级' }, ...] }
      levelProtectionOptions.value = res || []
    } else {
      console.warn('获取等保级别字典数据失败，使用默认选项')
    }
  } catch (error) {
    console.error('获取等保级别字典数据失败:', error)
    // 失败时使用默认选项
    levelProtectionOptions.value = [
      { label: '一级', value: '1' },
      { label: '二级', value: '2' },
      { label: '三级', value: '3' },
      { label: '四级', value: '4' },
      { label: '五级', value: '5' }
    ]
  }
}

// 提交表单
const handleSubmit = async (type: string) => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (formData.commitmentFile && formData.commitmentFile.id) {
      formData.commitmentFile = formData.commitmentFile.id.toString()
    }
    if (formData.applyFile && formData.applyFile.id) {
      formData.applyFile = formData.applyFile.id.toString()
    }

    // 准备提交数据
    const { useTime, ...otherFormData } = formData
    const submitData = {
      catalogId: route.params.id,
      ...otherFormData,
      useTimeStart: useTime[0],
      useTimeEnd: useTime[1],
      status: type,
      commitmentFile: formData.commitmentFile, // 保存ID用于提交
      applyFile: formData.applyFile // 保存ID用于提交
    }

    // 这里可以调用API提交表单数据
    await portalApi.updateApplication(submitData)

    ElMessage.success('申请提交成功')

    // 通知父组件表单已提交成功
    emit('formSubmitted')

    // 关闭表单弹窗
    handleCloseForm()
  } catch (error) {
    console.log('error', error)

    ElMessage.error('请完善表单信息')
  }
}

// 保存表单
const handleSave = async (type: string) => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()

    // 准备提交数据
    const { useTime, ...otherFormData } = formData

    if (formData.commitmentFile && formData.commitmentFile.id) {
      formData.commitmentFile = formData.commitmentFile.id.toString()
    }
    if (formData.applyFile && formData.applyFile.id) {
      formData.applyFile = formData.applyFile.id.toString()
    }

    const submitData = {
      catalogId: route.params.id,
      ...otherFormData,
      useTimeStart: useTime[0],
      useTimeEnd: useTime[1],
      status: type,
      commitmentFile: formData.commitmentFile, // 保存ID用于提交
      applyFile: formData.applyFile // 保存ID用于提交
    }

    // 这里可以调用API提交表单数据
    await portalApi.updateApplication(submitData)

    ElMessage.success('保存成功')

    // 通知父组件表单已保存成功
    emit('formSubmitted')

    // 关闭表单弹窗
    handleCloseForm()
  } catch (error) {
    console.log('error', error)
    ElMessage.error('请完善表单信息')
  }
}
const category = ref()
const type = ref()

// 打开表单弹窗并填充数据
const openDialog = async (params?: any) => {
  // 如果有参数传入
  if (params && params.catalogId && params.applicationType) {
    // debugger
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields()
    }

    type.value = params.applicationType

    try {
      // 显示加载状态
      // const loadingInstance = ElMessage.loading('加载申请信息中...', {
      //   duration: 0
      // })

      if (params.category == 'view') {
        category.value = true
      } else {
        category.value = false
      }

      try {
        // 在组件内部调用接口
        const response = await portalApi.applicationDetail({
          catalogId: params.catalogId,
          applicationType: params.applicationType
        })

        // 填充表单数据
        if (response) {
          Object.assign(formData, response)

          // 处理日期范围特殊字段
          if (response.useTimeStart && response.useTimeEnd) {
            formData.useTime = [response.useTimeStart, response.useTimeEnd]
          }
        }
      } finally {
        // 关闭加载状态
        // loadingInstance.close()
      }
    } catch (error) {
      console.error('获取申请详情失败:', error)
      ElMessage.error('获取申请详情失败，将打开空表单')
    }
  }

  // 打开弹窗
  showFormDialog.value = true
}

watch(
  () => formData.commitmentFile,
  (newValue) => {
    // 如果newValue是一个对象而不是字符串，说明传递的是完整文件信息
    if (typeof newValue === 'object' && newValue !== null) {
      formData.commitmentFile = newValue // 保存ID用于提交
    }
  },
  { deep: true }
)

watch(
  () => formData.applyFile,
  (newValue) => {
    // 如果newValue是一个对象而不是字符串，说明传递的是完整文件信息
    if (typeof newValue === 'object' && newValue !== null) {
      formData.applyFile = newValue // 保存ID用于提交
    }
  },
  { deep: true }
)

// 暴露方法给父组件
defineExpose({
  openForm,
  openDialog
})

onMounted(() => {
  getLevelProtectionOptions()
})
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
